/*
 * SearchBooks.fx
 * Author: Yu Min-ting
 * Created on 2009-7-13, 14:05:56
 */

package com.sjtu.fx.book;

import javafx.scene.*;

import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.*;
import javafx.stage.Stage;
import com.sjtu.fx.tools.Panel;
import javafx.ext.swing.SwingComboBox;
import javafx.ext.swing.SwingComboBoxItem;

import javafx.io.http.HttpRequest;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.json.JSONObject;

import org.json.JSONArray;

import java.lang.System;

import javafx.scene.image.Image;

import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import com.sjtu.fx.tools.SwingTextArea;
import com.sjtu.fx.book.WaitingList.BookLibraryInfo;
import com.sjtu.fx.comments.BookDetailsComments.Comment;
public class Results{
    public var id:String;
    public var url:String;
    public var title:String;
    public var author:String;
    public var publisher:String;
    public var score:String;
}



public class SearchBooks extends CustomNode{
     var panel:Panel;
  //   var searchResult:SearchResults;
     var choices : SwingComboBox = SwingComboBox {
         items: [
             SwingComboBoxItem {
                 text: "Book Name"
                 selected: true
             },
             SwingComboBoxItem { text: "Book ISBN" },
             SwingComboBoxItem { text: "Publisher" },
             SwingComboBoxItem { text: "Book Author"},
             SwingComboBoxItem { text: "key words"},
         ]
     }
     var content : TextBox = TextBox {
         promptText: "[A New Search keyword]"
         columns: 16
     }

    var search : Button = Button {
        text: "GO>"
        font: Font {size:11 name: "Verdana Bold"}
        action: function() {
            getSearchResult();
        }
    }


    var advanced : Hyperlink = Hyperlink {
        text: "Advanced Search"
        font: Font {size:11 name: "Verdana Bold"}
        action: function() {

        }
    }

    override protected function create() : Node {
        Group{
            content:[
                 panel = Panel {
                    width:    185
                    height:   150
                    title:    "Search Books"
                    translateX: 0
                    translateY: 0
                },

                 VBox{
                    spacing: 10
                    translateX:20 translateY: 45
                    content:[content,
                    HBox{
                        spacing:5
                        content:[choices,search]
                    }, advanced]

                },

            ]
        }
     }
     function getSearchResult(){
             HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/Search"

       onOutput: function(os:OutputStream) {
            try {
                var json:JSONObject = JSONObject{};
                json.put("searchType",choices.selectedItem.text);
                json.put("KeyWord",content.text);
                var temp:String = "obj={json.toString()}";
         //       System.out.println(temp);
                os.write(temp.getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }

        onInput: function(is: InputStream) {
            for (i in[1..6]){
                (this.parent.lookup("searchResult") as SearchResults).Images.content[0] = null;

            }
            try {
//              System.out.println("Here");
                def data:DataInputStream = new DataInputStream(is);
                var json:JSONObject = JSONObject{};
                var result:String = data.readLine();
                json = new JSONObject(result);
                System.out.println(json);
                var bookNamelist:JSONArray = json.getJSONArray("bookNameList");
                var authorlist:JSONArray = json.getJSONArray("authorList");
                var publisherList:JSONArray = json.getJSONArray("publisherList");
                var urlList:JSONArray = json.getJSONArray("urlList");
                var idList:JSONArray = json.getJSONArray("idList");
                var scoreList:JSONArray = json.getJSONArray("scoreList");
                var index:Integer = 0;
       //         searchResult = SearchResults{id:"searchResult"  translateX:225 translateY:135  visible:false}
                while(index<bookNamelist.length()){
       /*             System.out.println(bookNamelist.get(index));
                    System.out.println(authorlist.get(index));
                    System.out.println(publisherList.get(index));
                    System.out.println(urlList.get(index));
                    System.out.println(idList.get(index));
       */             var book:Results = Results{
                        id:idList.get(index).toString(),
                        url:urlList.get(index).toString(),
                        publisher: publisherList.get(index).toString(),
                        author: authorlist.get(index).toString(),
                        title:bookNamelist.get(index).toString(),
                        score:scoreList.get(index).toString()
                    };
                //    (this.parent.lookup("searchResult") as SearchResults).results[index] = book;
                    (this.parent.lookup("searchResult") as SearchResults).url[index]
                            =  urlList.get(index).toString() ;
                    (this.parent.lookup("searchResult") as SearchResults).author[index] 
                            = authorlist.get(index).toString();
                    (this.parent.lookup("searchResult") as SearchResults).publisher[index]
                            = publisherList.get(index).toString();
                    (this.parent.lookup("searchResult") as SearchResults).title[index]
                            = bookNamelist.get(index).toString();
                    (this.parent.lookup("searchResult") as SearchResults).bookid[index]
                            = idList.get(index).toString();
                    if(index<6){
                    var box:Group = Group{
                        id: index.toString()
                        content: [
                            HBox{
                                spacing: 10
                                content:[
                                    ImageView {
                                        onMouseClicked: function( e: MouseEvent ):Void {
                                   //         System.out.println("###Here###{bookNamelist.}");
                                            var i:Integer = Integer.parseInt(idList.get(Integer.parseInt(box.id)).toString());
                                            System.out.println(i);
                                            var boxid:Integer = Integer.parseInt(idList.get(Integer.parseInt(box.id)).toString());
                                            setBorrowBookPage(boxid,bookNamelist.get(Integer.parseInt(box.id)).toString(),authorlist.get(Integer.parseInt(box.id)).toString(),
                                                    publisherList.get(Integer.parseInt(box.id)).toString(),urlList.get(Integer.parseInt(box.id)).toString());
                                        }
                                        image: Image{url: "{__DIR__}{urlList.get(index).toString()}.jpg" }
                                    },
                                    SwingTextArea{
                                        text:
                                        "{bookNamelist.get(index)} \n·By {authorlist.get(index)}\n·Book Publisher:\n{publisherList.get(index)}"
                                        editable:false
                                    }
                                ]
                             }]};
                             (this.parent.lookup("searchResult") as SearchResults).Images.content[index+1] = box;
                       }
                      // System.out.println("{index}:{bookNamelist.get(index)}");
                       index++;
                }
                }
             finally {
                 this.parent.lookup("topBooks").visible = false;
                 this.parent.lookup("recommendBooks").visible = false;
                 this.parent.lookup("searchResult").visible = true;
                is.close();
            }
        }
    }.start();

     }

function setBorrowBookPage(id:Integer,bookname:String,bookauthor:String,bookpublsher:String,url:String){
    HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/BookDetail"
       onOutput: function(os:OutputStream) {
            try {
                var json:JSONObject = JSONObject{};
                json.put("bookId",id);
                System.out.println("setBorrowBookPageHere{id}");
                var temp:String = "obj={json.toString()}";
         //       System.out.println(temp);
                os.write(temp.getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }
        onInput: function(is: InputStream) {
            try {
                def data:DataInputStream = new DataInputStream(is);
                var json:JSONObject = JSONObject{};
                var result:String = data.readLine();
                System.out.println(result);
                json = new JSONObject(result);
                var description:String = json.getString("description");
                var score:Integer = json.getInt("score");
                var labels:String = json.getString("labels");
                var bookInfo:JSONArray = json.getJSONArray("booklendinfo");
                System.out.println("Heregogo{score}");
                (this.parent.lookup("borrowBook") as BookDetails).waitingList.availableNumber = Integer.parseInt(bookInfo.get(bookInfo.length()-1).toString());
                var booklibInfo:BookLibraryInfo[];
                var i:Integer = 0;
                while(i <bookInfo.length()-1){
                    var info:String[] =  bookInfo.get(i).toString().split("   ");
                    booklibInfo[i] =  BookLibraryInfo{
                            libraryName: info[0]
                            Numberinfo:  info[1]
                            };
                    i++;
                };
                (this.parent.lookup("borrowBook") as BookDetails).waitingList.bookInfo = booklibInfo;
                var BookDetail:BookDetails = this.parent.lookup("borrowBook") as BookDetails;
                BookDetail.visible = true;
                BookDetail.author = bookauthor;
                BookDetail.bookname = bookname;
                BookDetail.publisher = bookpublsher;
                BookDetail.isbn = json.getString("isbn");
                BookDetail.bookScore = score.toString();
                BookDetail.labels = labels;
                BookDetail.description = description;
                BookDetail.avgScore = json.getDouble("avgScore");
                BookDetail.waitingNumber = json.getInt("waitingNum");
                System.out.println("waitingNumber:{BookDetail.waitingNumber}");
                BookDetail.bookId = id;
           //     BookDetail.userId = this.parent.lookup("")
                System.out.println("url:{url}");
                BookDetail.coverURL = url;
                BookDetail.image = Image
                    {url:"{__DIR__}{url}.jpg"
                    };
                var commentInfo:Comment[];
                var commentNameList:JSONArray = json.getJSONArray("userNameList");
                var commentContentList:JSONArray = json.getJSONArray("commentList");
                var commentScoreList:JSONArray = json.getJSONArray("scoreList");
                var commentDateList:JSONArray = json.getJSONArray("dateList");
                i = 0;
                while(i <commentNameList.length()){
                    commentInfo[i] =  Comment{
                            userName: commentNameList.get(i).toString()
                            content:  commentContentList.get(i).toString()
                            score:    Integer.parseInt(commentScoreList.get(i).toString())
                            date:     commentDateList.get(i).toString()
                            };
                    i++;
                };
                BookDetail.comments.comments = commentInfo;
        //        BookDetail.image = ImageView {
        //            image: Image{
        //                    url:url
        //                }
         //           };
          //      BookDetail.
            } finally {
                this.parent.lookup("loginPanel").visible = false;
                 this.parent.lookup("userPanel").visible = false;
                 this.parent.lookup("adminPanel").visible = false;
                this.parent.lookup("searchResult").visible = false;
                is.close();
            }
        }
    }.start();
}


function run() {
    Stage {
       width: 350 height: 300
        scene: Scene {
            content: [
                SearchBooks {translateX: 40 translateY: 40}
            ]
        }
    }
}
}
